<?php
/**
 * 子任务表控制器
 */

namespace app\admin\controller;

use think\Request;
use app\common\model\UserSubOrder;
use app\common\model\UserAppraiseOrder;
use app\common\model\User;
use app\common\model\UserAgent;

use app\common\validate\UserSubOrderValidate;
use app\common\validate\UserAppraiseOrderValidate;

class UserSubOrderController extends Controller
{
    //列表
    public function index(Request $request, UserSubOrder $model)
    {
        $param = $request->param();
        $model  = $model->scope('where', $param);
        if (isset($param['export_data']) && $param['export_data'] == 1) {
            $header = ['ID','主任务id','粉丝id','子任务编号','购买日期','二维码','链接','订单编号','1 已转款','打款时间','换手次数','延时次数','0 未提交 1进行中  2已完成','创建时间',];
            $body   = [];
            $data   = $model->select();
            foreach ($data as $item) {
                $record       = [];
                $record['id'] = $item->id;
                $record['task_id'] = $item->task_id;
                $record['uid'] = $item->uid;
                $record['task_no'] = $item->task_no;
                $record['order_time'] = $item->order_time;
                $record['pic'] = $item->pic;
                $record['url'] = $item->url;
                $record['order_no'] = $item->order_no;
                $record['type_id'] = $item->ty_text;
                $record['is_cash'] = $item->is_cash_text;
                $record['cash_time'] = $item->cash_time;
                $record['trans_num'] = $item->trans_num;
                $record['delay_num'] = $item->delay_num;
                $record['status'] = $item->status_text;
                $record['create_time'] = $item->create_time;

                $body[]       = $record;
            }
            return $this->exportData($header, $body, 'user_sub_order-' . date('Y-m-d-H-i-s'));
        }
        $data = $model->paginate($this->admin['per_page'], false, ['query'=>$request->get()]);
        //关键词，排序等赋值
        $this->assign($request->get());

        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
        ]);
        return $this->fetch();
    }

    //添加
    public function add(Request $request, UserSubOrder $model, UserSubOrderValidate $validate)
    {
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('add')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }

            $result = $model::create($param);

            $url = URL_BACK;
            if(isset($param['_create']) && $param['_create']==1){
                $url = URL_RELOAD;
            }

            return $result ? success('添加成功',$url) : error();
        }

        return $this->fetch();
    }

    //修改
    public function edit($id, Request $request, UserSubOrder $model, UserSubOrderValidate $validate)
    {
        $data = $model::get($id);
        if ($request->isPost()) {
            $param           = $request->param();
            $validate_result = $validate->scene('edit')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }

            $result = $data->save($param);
            return $result ? success() : error();
        }

        $this->assign([
            'data' => $data,
        ]);

        return $this->fetch('add');
    }

    //删除
    public function del($id, UserSubOrder $model)
    {
        if (count($model->noDeletionId) > 0) {
            if (is_array($id)) {
                if (array_intersect($model->noDeletionId, $id)) {
                    return error('ID为' . implode(',', $model->noDeletionId) . '的数据无法删除');
                }
            } else if (in_array($id, $model->noDeletionId)) {
                return error('ID为' . $id . '的数据无法删除');
            }
        }

        if ($model->softDelete) {
            $result = $model->whereIn('id', $id)->useSoftDelete('delete_time', time())->delete();
        } else {
            $result = $model->whereIn('id', $id)->delete();
        }

        return $result ? success('操作成功', URL_RELOAD) : error();
    }

    //评价任务
    public function evaluate($id, Request $request,  UserAppraiseOrderValidate $validate)
    {
        //子任务编号
        $bh = UserSubOrder::get($id);
        $this->assign('bh',$bh);

        $data = UserAppraiseOrder::where('order_id',$id)->find();
        if ($request->isPost()) {

            $param           = $request->param();
            $validate_result = $validate->scene('evaluate')->check($param);
            if (!$validate_result) {
                return error($validate->getError());
            }
            //处理截图列表上传
            if (!empty($_FILES['pics']['name'])) {
                $attachment_pics = new \app\common\model\Attachment;
                $file_pics       = $attachment_pics->upload('pics');
                if ($file_pics) {
                    $param['pics'] = $file_pics->url;
                }
            }

            //处理视频上传
            if (!empty($_FILES['video']['name'])) {
                $attachment_video = new \app\common\model\Attachment;
                $file_video       = $attachment_video->upload('video');
                if ($file_video) {
                    $param['video'] = $file_video->url;
                }
            }

            $param['comments'] = $request->param(false)['comments'];

            $result = UserAppraiseOrder::create($param);
            return $result ? success() : error();
        }

        $this->assign([
            'data' => $data
        ]);

        return $this->fetch('evaluate');
    }

    //批量分配任务给粉丝
    public function batch($id, UserSubOrder $model)
    {
        //查找满足粉丝数
        //今日时间
        $to_day = strtotime(date('Y-m-d'));
        $to_where = array(
            array('gt',$to_day),
            array('elt',$to_day+3600*24)
        );
        //今日预约
        $u_where = array(
            'order_time'=> $to_where,
        );

        $fid = UserBook::where($u_where)->select();
        $aid = [];
        foreach ($fid as $k=>$val)
        {
            $aid[] = $val;
        }
        var_dump($fid);die;
        var_dump(count($id));
        var_dump($id);die;
    }

    //补运费及差价
    public function userMoney(Request $request, UserSubOrder $model)
    {
        $param = $request->param();
        if($request->isPost())
        {
            $radio = $param['radio'];
            $price = $param['price'];
            $zid = $param['zid'];

            //查找该信息是否存在
            $res = UserSubOrder::find($zid);
            if(!$res)
            {
                return json(["errorCode"=>200,"msg"=>"该条数据异常，请刷新重试！"]);die;
            }

            //查找粉丝ID，根据粉丝ID查找分站站长ID
            $uid = $res['uid'];
            $fzid = User::where('id',$uid)->value('pid');
            if(!$fzid)
            {
                return json(["errorCode"=>200,"msg"=>"该子任务还没有分配,请分配后再给分站站长补差价！"]);die;
            }

            // 启动事务
            Db::startTrans();
            try{

                $zname = UserAgent::find($fzid);
                //站长充值后总金币
                $zMoney = $zname['user_money']+$price;

                //审核成功
                $auditData = [
                    'type_id'=>$radio,
                    'is_cash'=>1
                ];

                //1 差价
                if($radio==1)
                {
                    //平台流水记录
                    $dataUpdate = [
                        'amount'=>$price,
                        'note'=>"管理员已对站长".$zname['username']."补差价为".$price,
                        'create_time'=>time(),
                    ];

                    //站长流水记录-通过
                    $zData = [
                        'uid'=>$fzid,
                        'amount'=>$price,
                        'type'=>1,
                        'note'=>"站长".$zname['username']."补差价为".$price."现金币余额为".$zMoney."元",
                        'create_time'=>time(),
                    ];
                }else if($radio==2){ //运费
                    //平台流水记录
                    $dataUpdate = [
                        'amount'=>$price,
                        'note'=>"管理员已对站长".$zname['username']."补运费为".$price,
                        'create_time'=>time(),
                    ];

                    //站长流水记录-通过
                    $zData = [
                        'uid'=>$fzid,
                        'amount'=>$price,
                        'type'=>1,
                        'note'=>"站长".$zname['username']."补运费为".$price."现金币余额为".$zMoney."元",
                        'create_time'=>time(),
                    ];
                }

                Db::table('user_sub_order')->where('id',$zid)->update($auditData);
                Db::table('user_agent')->where('id',$fzid)->update(['user_money'=>$zMoney]);
                Db::table('admin_money_record')->insert($dataUpdate);
                Db::table('user_money_record')->insert($zData);

                // 提交事务
                Db::commit();
                return json(["errorCode"=>200,"msg"=>"恭喜，审核成功！"]);die;
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(["errorCode"=>200,"msg"=>"抱歉，审核失败！"]);die;
            }
        }
    }

    //状态-审核
    public function userExam(Request $request, UserSubOrder $model)
    {
        $param = $request->param();
        if($request->isPost())
        {
            $status = $param['status'];
            $tid = $param['tid'];

            //查找该信息是否存在
            $res = UserSubOrder::find($tid);
            if(!$res)
            {
                return json(["errorCode"=>200,"msg"=>"该条数据异常，请刷新重试！"]);die;
            }

            //审核成功
            $auditData = [
                'status'=>$status
            ];

            $re = UserSubOrder::where('id',$tid)->update($auditData);
            if($re)
            {
                return json(["errorCode"=>200,"msg"=>"恭喜，审核成功！"]);die;
            }else{
                return json(["errorCode"=>200,"msg"=>"抱歉，审核失败！"]);die;
            }
        }
    }

}